"""回收站数据模型"""
from datetime import datetime, timedelta
from ..timezone_utils import now as timezone_now
from . import db

class RecycleBin(db.Model):
    """回收站模型 - 存储被删除的脚本文件和文件夹"""
    __tablename__ = 'recycle_bin'
    
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    
    # 原始信息
    original_name = db.Column(db.String(255), nullable=False)  # 原始文件/文件夹名称
    original_path = db.Column(db.Text, nullable=False)  # 原始路径
    original_folder_id = db.Column(db.Integer)  # 原始所在文件夹ID
    item_type = db.Column(db.String(20), nullable=False)  # 'file' 或 'folder'
    
    # 删除信息
    deleted_at = db.Column(db.DateTime, nullable=False, default=timezone_now)
    deleted_by = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    
    # 存储的数据
    content_data = db.Column(db.Text)  # 文件内容或文件夹结构的JSON
    meta_data = db.Column(db.Text)  # 额外的元数据（JSON格式）
    
    # 关联关系
    user = db.relationship('User', foreign_keys=[user_id], backref='recycle_items')
    deleted_by_user = db.relationship('User', foreign_keys=[deleted_by])
    
    def __repr__(self):
        return f'<RecycleBin {self.original_name}>'
    
    @property
    def is_expired(self):
        """检查是否已过期（30天）"""
        from ..timezone_utils import naive_to_aware
        
        # 确保deleted_at有时区信息
        if self.deleted_at.tzinfo is None:
            deleted_at_aware = naive_to_aware(self.deleted_at)
        else:
            deleted_at_aware = self.deleted_at
            
        expiry_date = deleted_at_aware + timedelta(days=30)
        return timezone_now() > expiry_date
    
    @property
    def days_remaining(self):
        """剩余天数"""
        from ..timezone_utils import naive_to_aware
        
        # 确保deleted_at有时区信息
        if self.deleted_at.tzinfo is None:
            deleted_at_aware = naive_to_aware(self.deleted_at)
        else:
            deleted_at_aware = self.deleted_at
            
        expiry_date = deleted_at_aware + timedelta(days=30)
        remaining = expiry_date - timezone_now()
        return max(0, remaining.days)
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'user_id': self.user_id,
            'original_name': self.original_name,
            'original_path': self.original_path,
            'item_type': self.item_type,
            'deleted_at': self.deleted_at.isoformat() if self.deleted_at else None,
            'deleted_by': self.deleted_by,
            'deleted_by_username': self.deleted_by_user.username if self.deleted_by_user else None,
            'is_expired': self.is_expired,
            'days_remaining': self.days_remaining,
            'meta_data': self.meta_data
        }
    
    @classmethod
    def cleanup_expired(cls):
        """清理过期的回收站项目"""
        expiry_date = timezone_now() - timedelta(days=30)
        expired_items = cls.query.filter(cls.deleted_at < expiry_date).all()
        
        for item in expired_items:
            db.session.delete(item)
        
        db.session.commit()
        return len(expired_items)